import {astar} from "./astar";
import {
    RenderableBehaviour,
    SerilizeField,
    core,
    Transform
} from "./gameengine";

import {Rect_Collider} from "./collider/rect_Collider";
import {colliderPrefab} from "./prefab";
import {createTileMapItemPrefab} from "./data/data";

var tileMapData=[];
var objs=[];

export const propertyEditor_TileMap = (host, script, key) => {
    tileMapData=script[key];

    var value = script[key][0];
    const newLine=[0,0,0,0,0,0];
    var obj = {
        'line1': value.join(","),
        'line': newLine.join(","),
        'addbutton': () => {
            const controller=host.scriptRoot.add(obj,"line");
            controller.onFinishChange(onFinishChanged);
        }
    };

    for(var i=0;i<script[key].length;i++){
        var obj2={
            "line":tileMapData[i].join(",")
        };

        objs.push(obj2);
    }

    host.scriptRoot.add(obj, 'addbutton');

    for(var i=0;i<script[key].length;i++){

        const controller = host.scriptRoot.add(objs[i],"line");
        controller.onFinishChange(onFinishChanged);
        controller.onChange(function (value) {
            console.log("host:");
            console.log(host);
            console.log("value");
            console.log(value);
            console.log(key, value);
        });
    }

    function onFinishChanged(value) {

        const m=this.domElement.parentNode.parentNode;
        const children=this.domElement.parentNode.parentNode.parentNode.children;

        var index=-1;
        for(var i=0;i<children.length;i++){
            if(children[i]==m){
                index=i;
            }
        }

        const currentData = value.split(",").map(item => {
            return parseInt(item);
        });

        const arr=tileMapData;
        tileMapData[index-2]=currentData;
        arr[index-2]=currentData;

        var isValid=true;
        for(var  i=0;i<arr.length;i++){
            for(var j=0;j<arr[i].length;j++){
                if(arr[i][j]!=0&&arr[i][j]!=1&&arr[i][j]!=2&&arr[i][j]!=3&&arr[i][j]!=4&&arr[i][j]!=5){
                    isValid=false;
                }
            }
        }

        if (isValid) {
            host.save(key, arr);
        } else {
            alert("非法数据")
        }
    }
};

export class TileMapRenderer extends RenderableBehaviour {

    @SerilizeField(propertyEditor_TileMap)
    tileData: number[][] = [];

    public grid: astar.Grid;
    public width:number;
    public height:number;

    onStart() {

        //获取地图的长宽
        let xlength: number = 0;
        let ylength: number = 0;


        // createPrefab from tileData

        for (let rowIndex = 0; rowIndex < this.tileData.length; rowIndex++) {
            const row = this.tileData[rowIndex];
            ylength = this.tileData.length;
            xlength = row.length;
            for (let colIndex = 0; colIndex < row.length; colIndex++) {
                const data = row[colIndex];
                const gameObjectPrefabData = createTileMapItemPrefab(data);
                const gameObject = core.createPrefab(gameObjectPrefabData);
                const type = row[colIndex];
                this.addCollider(type, colIndex, rowIndex);
                this.displayObject.addChild(gameObject);
                const transform = gameObject.getScript(Transform);
                transform.x = colIndex * 64;
                transform.y = rowIndex * 64;

            }
        }

        this.displayObject.renderNode = this;
        // console.log(xlength,ylength);
        this.grid = new astar.Grid(xlength, ylength);

        this.width=xlength*64;
        this.height=ylength*64;
        console.log("width:"+xlength*64);

        console.log(this.getRenderArea()) 
    }

    addCollider(type: any, x: number, y: number) {
        const mapCollider = core.createPrefab(colliderPrefab);
        const colliderTransform = mapCollider.getScript(Transform);
        const rectCollider = new Rect_Collider();
        rectCollider.type = 1;
        if (type == 2 || type==3 ||type==4 || type==5 ||type==8||type==9 || type==10 ||type==21||type==22 ||type==23 ||type==24 ||type==25||type==27||type==28||type==31||type==41||type==51||type==101||type==504||type==509) {    //顶部墙
            mapCollider.id = type;
            colliderTransform.x = x * 64;
            colliderTransform.y = y * 64;
            rectCollider.width = 64;
            rectCollider.height = 64;
        } else if (type == 1 || type==6||type==508||type==501) {     //左侧墙
            mapCollider.id = type;
            colliderTransform.x = x * 64;
            colliderTransform.y = y * 64;
            rectCollider.width = 38;
            rectCollider.height = 64;
        } else if (type == 506) {     //左侧墙
            mapCollider.id = type;
            colliderTransform.x = x * 64;
            colliderTransform.y = y * 64;
            rectCollider.width = 47;
            rectCollider.height = 64;
        } else if (type == 4 ||type==11||type==61||type==71||type==502||type==503||type==505) {     //右侧墙
            mapCollider.id = type;
            colliderTransform.x = x * 64 + 26;  //26是64-38
            colliderTransform.y = y * 64;
            rectCollider.width = 38;
            rectCollider.height = 64;
        } else if (type == 507) {     //右侧墙
            mapCollider.id = type;
            colliderTransform.x = x * 64 + 17;
            colliderTransform.y = y * 64;
            rectCollider.width = 47;
            rectCollider.height = 64;
        }
        mapCollider.addScript(rectCollider);
        this.displayObject.addChild(mapCollider);
        // console.log(this.displayObject.children);

    }

    onUpdate() {
    }


    onPropertyChanged(key: string, value: any) {
        if (key === "tileData") {
            this.displayObject.removeAllChildren();
            for (let rowIndex = 0; rowIndex < this.tileData.length; rowIndex++) {
                const row = this.tileData[rowIndex];
                for (let colIndex = 0; colIndex < row.length; colIndex++) {
                    const data = row[colIndex];
                    const gameObjectPrefabData = createTileMapItemPrefab(data);
                    const gameObject = core.createPrefab(gameObjectPrefabData);
                    this.displayObject.addChild(gameObject);
                    const transform = gameObject.getScript(Transform);
                    transform.x = colIndex * 64;
                    transform.y = rowIndex * 64;
                }
            }
        }
        console.log('属性改变', key, value)
    }

    onRender(context: CanvasRenderingContext2D) {
        // for (let rowIndex = 0; rowIndex < this.tileData.length; rowIndex++) {
        //     const row = this.tileData[rowIndex];
        //     for (let colIndex = 0; colIndex < row.length; colIndex++) {
        //         const data = row[colIndex];
        //         const imageUrl = `assets/tilemap/${data}.png`;
        //         const image = getImage(imageUrl);
        //         context.drawImage(image, colIndex * 64, rowIndex * 64);
        //     }
        // }
    }


    public getRenderArea() {
        return {
            x: 0,
            y: 0,
            width: this.tileData[0].length*64,
            height: this.tileData.length*64
        }
    }
}